<script setup lang="ts">
import type { CodeMateProject } from '@/apis/code/codeMateApi'
import type { DataAction } from '@/components/DataForm/types'
import { inject, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { codeMateProjectApi } from '@/apis/code/codeMateApi'
import { useEditForm } from '@/components/DataForm/useEditForm'
import { codeProjectFields } from './codeMate'
import CodeModuleTable from './CodeModuleTable.vue'

const { data } = defineProps<{ data: CodeMateProject }>()

const emits = defineEmits(['remove'])

const {
  editFormData,
  submitEditForm,
  EditForm,
} = useEditForm<CodeMateProject>({
  editFields: codeProjectFields,
})

const api = codeMateProjectApi
const router = useRouter()

const loadProjectData = inject<() => Promise<void>>('loadProjectData')
const actions = reactive <Record<string, DataAction>>({
  create: {
    label: '创建',
    type: 'primary',
    authCode: 'code:mate:module:create',
    click: () => submitEditForm('新增', api.create),
    success: async (data) => {
      router.push(`/code/mate/module/${data.projectName}`)
    },
  },
  modify: {
    label: '保存',
    type: 'primary',
    authCode: 'code:mate:module:modify',
    click: () => submitEditForm('编辑', api.modify),
    success: loadProjectData,
  },
  remove: {
    label: '删除',
    type: 'danger',
    authCode: 'code:mate:project:remove',
    confirm: '删除不可恢复，请谨慎确认',
    click: data => api.remove(data.id),
    success: async () => {
      loadProjectData && await loadProjectData()
      emits('remove')
    },
    message: true,
  },
})
onMounted(() => editFormData.value = data)
</script>

<template>
  <div class="flex flex-row justify-end">
    <data-button v-if="editFormData.id !== undefined" v-model="editFormData" :action="actions.remove" />
    <data-button v-if="editFormData.id !== undefined" v-model="editFormData" :action="actions.modify" />
    <data-button v-if="editFormData.id === undefined" v-model="editFormData" :action="actions.create" />
  </div>

  <EditForm />

  <CodeModuleTable
    v-if="editFormData.moduleList && editFormData.id"
    :data="editFormData.moduleList"
    :parent-id="editFormData.id"
  />
</template>
